<?php
include("dbconnect.php");
include("uploadFile.php");

$debugOn = true;

//This must be done before ANY html is output, which is why it's right at the top!
if ($_REQUEST['submit'] == "X")
{
	$sql = "DELETE FROM Products WHERE ProductID = '$_REQUEST[id]'";
	if ($dbh->exec($sql))
		header("Location: admin.php"); 
}
?>

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>PHP SQLite Database Shop TEST - Results Page</title>
</head>
<body>
<h1>Results</h1>

<?php
echo "<h2>Form Data</h2>";
echo "<pre>";
print_r($_REQUEST); // a useful debugging function to see everything in an array, best inside a <pre> element
echo "</pre>";

// If the insert button was pressed.
if ($_REQUEST['submit'] == "Upload")
{
	$sql = "INSERT INTO Products (ProductName,Colour,Size,ProductDescription,UnitPrice,UnitsInStock,Dimensions,Weight) 
VALUES ('$_REQUEST[name]','$_REQUEST[colour]','$_REQUEST[size]','$_REQUEST[description]','$_REQUEST[price]','$_REQUEST[units]','$_REQUEST[dimensions]','$_REQUEST[weight]')";
	
	echo "<p>Query: " . $sql . "</p>\n<p><strong>"; 
	if ($dbh->exec($sql))
		echo "Inserted $_REQUEST[ProductName]";
	else
		echo "Not inserted"; // in case it didn't work - e.g. if database is not writeable
}

// If the delete button was pressed.
else if ($_REQUEST['submit'] == "Delete Entry")
{
	$sql = "DELETE FROM Products WHERE ProductID = '$_REQUEST[id]'";
	echo "<p>Query: " . $sql . "</p>\n<p><strong>"; 
	if ($dbh->exec($sql))
		echo "Deleted $_REQUEST[name]";
	else
		echo "Not deleted";
}

// If the update button was pressed.
else if ($_REQUEST['submit'] == "Update Entry")
{
	$sql = 
	"UPDATE Products SET ProductName = '$_REQUEST[name]', Colour = '$_REQUEST[colour]', Size = '$_REQUEST[size]', 
	ProductDescription = '$_REQUEST[description]', UnitPrice = '$_REQUEST[price]', UnitsInStock = '$_REQUEST[units]',Dimensions = '$_REQUEST[dimensions]', Weight = '$_REQUEST[weight]'";
	 
	echo "<p>Query: " . $sql . "</p>\n<p><strong>"; 
	
	if ($dbh->exec($sql))
		echo "Updated $_REQUEST[name]";
	else
		echo "Not updated";
}
else {
	echo "This page did not come from a valid form submission.<br />\n";
}
echo "</strong></p>\n";


// Basic select and display all contents from table 
echo "<h2>Product Records in Database Now</h2>\n";
$sql = "SELECT * FROM Products";
$result = $dbh->query($sql);
$resultCopy = $result;

if ($debugOn) {
	echo "<pre>";	
	
// all rows in one associative array
	$rows = $result->fetchall(PDO::FETCH_ASSOC);
	echo count($rows) . " records in table<br />\n";
	print_r($rows);
	echo "</pre>";
	echo "<br />\n";
}

foreach ($dbh->query($sql) as $row)
{
	print $row[name] .' - '. $row[colour] .' - '. $row[description] . ' - '. $row[price] . ' - '. $row[units] . ' - '. $row[dimensions] . ' - '. $row[weight] ."<br />\n";
}

// close the database connection 
$dbh = null;
?>
<p><a href="admin.php">Return to database test page</a></p>
</body>
</html>